import { defineComponent, PropType, reactive, ref, toRefs } from 'vue'
import {
  NInput,
  NForm,
  NFormItem,
  NModal,
  FormRules,
  NSelect,
  SelectOption
} from 'naive-ui'
import { Response } from '@/service/modules/common/types'
import { saveOrUpdateTaskReq } from '@/service/modules/task-manage'
import { getProUserListReq } from '@/service/modules/user'
import { SelectMixedOption } from 'naive-ui/es/select/src/interface'
import { TaskDefined } from '@/service/modules/task-manage/types'

const ModTasktModal = defineComponent({
  name: 'ModTasktModal',
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    taskTypes: {
      type: Array<String>,
      required: true
    },
    taskDefined: {
      type: Object as PropType<TaskDefined>,
      required: true
    }
  },
  emits: ['modalShowChange', 'refreshList'],
  setup() {
    const state = reactive({
      form: {
        id: 0,
        name: '',
        description: '',
        taskType: '',
        owners: [] as string[]
      },
      positiveButtonDisabled: ref(false),
      rules: {
        name: {
          trigger: ['input', 'blur'],
          required: true,
          validator() {
            if (state.form.name === '') {
              return new Error(window.$t('taskManage.taskNameTips'))
            }
          }
        },
        taskType: {
          trigger: ['input', 'blur'],
          required: true,
          validator() {
            if (state.form.name === '') {
              return new Error(window.$t('taskManage.taskTypeTips'))
            }
          }
        }
      } as FormRules
    })
    const loadingRef = ref(false)
    const optionsRef = ref<SelectOption[]>([])
    return {
      ...toRefs(state),
      loadingRef,
      optionsRef
    }
  },
  updated() {
    this.form.id = this.taskDefined.id
    this.form.name = this.taskDefined.name
    this.form.description = this.taskDefined.description
    this.form.taskType = this.taskDefined.taskType
    this.form.owners = this.taskDefined.owners
  },
  mounted() {
    this.getProMenbers()
  },
  methods: {
    async onPositiveClick() {
      //输入框存在为空时则确认按钮无效
      if (this.form.name === '' || !this.form.taskType) {
        return
      }
      //提交修改作业请求
      this.positiveButtonDisabled = true
      const res: Response<any> = await saveOrUpdateTaskReq({
        ...this.form
      }).catch(() => {
        this.positiveButtonDisabled = false
      })
      if (res.resp_code === 0) {
        this.initData()
        this.$emit('modalShowChange', false)
        this.$emit('refreshList')
        this.positiveButtonDisabled = false
      } else {
        this.positiveButtonDisabled = false
      }
    },
    onNegativeClick() {
      this.initData()
      this.$emit('modalShowChange', false)
    },
    initData() {
      this.form.id = 0
      this.form.name = ''
      this.form.description = ''
      this.form.taskType = ''
      this.form.owners = []
    },
    async getProMenbers() {
      const res = await getProUserListReq({
        page: 1,
        limit: -1,
        proId: window.$store.state.userInfo.currentProjectId
      })
      if (res.resp_code === 0) {
        this.optionsRef = res.data
      }
      this.loadingRef = false
    }
  },
  render() {
    return (
      <NModal
        show={this.showModal}
        mask-closable={false}
        style='width: 400px'
        title={window.$t('taskManage.createTask')}
        bordered={false}
        size='huge'
        preset='dialog'
        positive-text={window.$t('dialog.positiveText')}
        negative-text={window.$t('dialog.negativeText')}
        onPositiveClick={this.onPositiveClick}
        onNegativeClick={this.onNegativeClick}
        positiveButtonProps={{
          disabled:
            this.positiveButtonDisabled ||
            this.form.name === '' ||
            this.form.taskType === ''
        }}
        onClose={this.onNegativeClick}
      >
        <NForm
          rules={this.rules}
          label-placement='left'
          require-mark-placement='right-hanging'
          label-width='auto'
        >
          <NFormItem path='name' label={window.$t('taskManage.taskName')}>
            <NInput
              type='text'
              v-model={[this.form.name, 'value']}
              placeholder={window.$t('taskManage.taskNameTips')}
              autofocus
            />
          </NFormItem>
          <NFormItem path='description' label={window.$t('common.description')}>
            <NInput
              type='textarea'
              v-model={[this.form.description, 'value']}
            />
          </NFormItem>

          <NFormItem path='taskType' label={window.$t('taskManage.taskType')}>
            <NSelect
              v-model={[this.form.taskType, 'value']}
              options={this.taskTypes.map((item) => {
                return {
                  label: item,
                  value: item
                } as SelectMixedOption
              })}
              size='small'
              placeholder={window.$t('taskManage.taskTypeTips')}
              disabled={true}
            />
          </NFormItem>
          <NFormItem path='owners' label={window.$t('common.owners')}>
            <NSelect
              v-model:value={this.form.owners}
              filterable
              multiple
              options={this.optionsRef}
              label-field='username'
              value-field='username'
              loading={this.loadingRef}
              clearable
            ></NSelect>
          </NFormItem>
        </NForm>
      </NModal>
    )
  }
})

export default ModTasktModal
